/* eslint-disable no-negated-condition */
import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {Button, Form, Row, Col, Card, Spin, message as msg} from 'antd';
import {getDetail} from './api';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {hasPermissions} from './utils';
import {PERMISSIONS} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, language} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import FileUpload from './FileUpload';
import SearchInput from 'Shared/components/SearchInput';
import {PDICheckResult} from '../Enum';
import SaleShipmentPanel from './SaleShipmentPanel';
import moment from 'moment';
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {
            pdiCheckResult: PDICheckResult.完好,
            checkTime: moment().format('YYYY-MM-DD')
        },
        showSaleShipmentPanel: false
    };

    componentDidMount() {
        this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }
    getDetailInfo = () => {
        if(this.props.id)
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            isFetching: false,
                            data: res.data
                        });
                    else
                        this.setState(({
                            isFetching: false
                        }));
                });
    }
    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                }
            };
        });
    };
    onClickSearchSaleShipmentBtn = () => {
        if(!this.state.data.dealerId)
            msg.warn(this.props.intl.formatMessage({
                id: 'NewPanel.message.choseDealer',
                defaultMessage: '请先选择总代'
            }));
        if(this.state.data.dealerId)
            this.setState({showSaleShipmentPanel: true});
    }
    onCloseSaleShipmentPanel = () => {
        this.setState({showSaleShipmentPanel: false});
    }
    onSelectAddedSaleShipment = records => {
        this.setState({
            data: Object.assign({}, this.state.data, {
                saleShipmentId: records.id,
                saleShipmentCode: records.code,
                vin: records.vin
            }),
            hasOperat: true,
            showSaleShipmentPanel: false
        });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        this.setState({
            data: {
                ...data,
                attachments
            },
            hasOperat: true,
        });
    }
    render() {
        const {data} = this.state;
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const validateBrand = !data.brandId && this.state.validate ? 'error' : null;
        const validateDealer = !data.dealerId && this.state.validate ? 'error' : null;
        const validateSaleShipment = !data.saleShipmentId && this.state.validate ? 'error' : null;
        const validateVin = !data.vin && this.state.validate ? 'error' : null;
        const validatePdiCheckResult = !data.pdiCheckResult && this.state.validate ? 'error' : null;
        const {formatMessage} = this.props.intl;
        const {pagePermission} = this.props;
        const submitable = hasPermissions(PERMISSIONS.add, pagePermission);
        if(this.props.initEnum.brands.length === 1 && !this.props.id)
            data.brandId = this.props.initEnum.brands[0].value;
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Form>
                        <Card {...FORM_OPTIONS.col} title={formatMessage({
                            id: 'newPanel.card.title',
                            defaultMessage: '基本信息'
                        })}>
                            <Row>
                                {this.props.initEnum.brands.length !== 1 &&
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.brand',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateBrand} required>
                                        {!this.props.id ? <WrappedSelect
                                            allowClear
                                            name="brandId"
                                            value={data.brandId}
                                            options={this.props.initEnum.brands}
                                            disabled={this.props.initEnum.brands.length === 1}
                                            onChange={this.handleFilterChange}/>
                                            : `(${data.brandCode})${data.brandName}`
                                        }
                                    </FormItem>
                                </Col>
                                }
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                        <DealerSelectPanel
                                            value={dealerInfo}
                                            onChange={this.handleFilterChange}
                                            onSelect={this.onSelectDealer} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'addPanel.data.saleShipmentId',
                                        defaultMessage: '发运单编号'
                                    })}{...FORM_OPTIONS.item} validateStatus={validateSaleShipment} required>
                                        {!this.props.id ? <SearchInput
                                            disabled={true}
                                            value={data.saleShipmentCode}
                                            onChange={this.handleFilterChange}
                                            onClickSearchBtn={this.onClickSearchSaleShipmentBtn} />
                                            : data.saleShipmentCode
                                        }
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.vin',
                                            defaultMessage: 'VIN '
                                        })}
                                        {...FORM_OPTIONS.item} validateStatus={validateVin} required>
                                        {data.vin}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.PdiCheckResult',
                                            defaultMessage: '检查结果'
                                        })} {...FORM_OPTIONS.item} validateStatus={validatePdiCheckResult} required>
                                        <WrappedSelect
                                            allowClear
                                            name="pdiCheckResult"
                                            value={data.pdiCheckResult}
                                            options={PDICheckResult.toList(language)}
                                            onChange={this.handleFilterChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.checkMan',
                                            defaultMessage: '检查人姓名'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="checkMan"
                                            value={data.checkMan}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.checkTime',
                                            defaultMessage: '检查时间'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="checkTime"
                                            value={data.checkTime}
                                            onChange={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'newPanel.form.remark',
                                            defaultMessage: '备注'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="remark"
                                            value={data.remark}
                                            onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card title={formatMessage({
                            id: 'reportPanel.title.files',
                            defaultMessage: '附件清单'
                        })}>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FileUpload onChange={this.onChangeUpload}
                                        onRemove={this.removeFilePath}
                                        fileList={data.attachments || []}/>
                                </Col>
                            </Row>
                        </Card>
                        <Card type="inner">
                            <Row>
                                <Col disabled={!submitable} className="col-align-right">
                                    <Button key="submit" loading={this.state.loading}
                                        onClick={this.onSubmit} type="primary">{formatMessage({
                                            id: 'newPanel.btn.submit',
                                            defaultMessage: '保存'
                                        })}</Button>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                {
                    this.state.showSaleShipmentPanel &&
                        <SaleShipmentPanel
                            selectKey={data.id}
                            dealerId={data.dealerId}
                            onCancel={this.onCloseSaleShipmentPanel}
                            onSelect={this.onSelectAddedSaleShipment} />
                }
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

NewPanel.propTypes = {
    initEnum: PropTypes.object.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
import {createSelector} from 'reselect';
const getinitEnumData = createSelector(
    state => state.getIn(['page', 'domainData', 'initData']),
    init => {
        const initData = init.toJS();
        const brands = initData.brands
            ? initData.brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : [];
        return {
            brands,
        };
    }
);
const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    initEnum: getinitEnumData(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onSubmit(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url()),
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
